package com.shopx.core.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

/**
 * 图形验证码
 *
 * @author:lituo
 * @date:2021/12/9
 **/
public class GraphicHelper {

  /**
   * 生成图形验证码
   *
   * @param width
   * @param height
   * @param output
   * @return java.lang.String
   * @author lituo
   * @date 9:08 PM 2021/12/9
   */
  public static String genCode(int width, int height, OutputStream output) {
    StringBuffer sb = new StringBuffer();
    Random random = new Random();
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics graphic = image.getGraphics();
    graphic.setColor(Color.getColor("F8F8F8"));
    graphic.fillRect(0, 0, width, height);
    Color[] colors = new Color[]{Color.BLUE, Color.RED, Color.BLACK};
    for (int i = 0; i < 50; i++) {
      graphic.setColor(colors[random.nextInt(colors.length)]);
      final int x = random.nextInt(width);
      final int y = random.nextInt(height);
      final int w = random.nextInt(20);
      final int h = random.nextInt(20);
      final int signA = random.nextBoolean() ? 1 : -1;
      final int signB = random.nextBoolean() ? 1 : -1;
      graphic.drawLine(x, y, x + w * signA, y + h * signB);
    }
    graphic.setFont(new Font("Comic Sans MS", Font.BOLD, 30));
    for (int i = 0; i < 4; i++) {
//      final int temp = random.nextInt(26) + 97;
//      String s = String.valueOf((char) temp);
      String s = String.valueOf(random.nextInt(9)+1);
      sb.append(s);
      graphic.setColor(colors[random.nextInt(colors.length)]);
      graphic.drawString(s, i * (width / 6), height - (height / 3));
    }
    graphic.dispose();
    try {
      ImageIO.write(image, "jpeg", output);
    } catch (IOException e) {
      e.printStackTrace();
    }
    return sb.toString();
  }

  public static void main(String argsp[]){
    Random random = new Random();
    System.out.print(random.nextInt(9)+1);
  }
}
